package com.pb.infra.oth.util;

import com.pb.infra.oth.entity.FileDirVO;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Slf4j
public class ExecuteScriptUtil {

    /**
     * 全局变量: 错误代码、错误说明
     */

    public static final int FAIL = -1;
    public static String DATETIMESIMPLEFORMAT = "yyyyMMddHHmmssSSS";
    public static Properties etljob_cfg = null;//规则资料库
    public static String DB_TYPE;


    /**
     * @param params  新进程参数
     * @param logFlag 主线程是否接收日志 1:是 0:否
     */
    public static int runJobCmd(List<String> params, boolean logFlag) {

        int exitValue;
        ProcessBuilder builder = new ProcessBuilder(params);
        builder.redirectErrorStream(true);
        Process p = null;
        log.debug("进入挂起主线程时显示参数:{}", params);
        try {

            p = builder.start();
            if (logFlag) {
                new CleanInputCache(p.getInputStream(), "INFO").start();
                new CleanInputCache(p.getErrorStream(), "ERROR").start();
            }
            //将当前线程等待，直到执行完成.
//            if(logFlag){
//            //设置最长等待时间
            p.waitFor();
//            }
            log.debug("1.是否挂起主线程?");
            exitValue = p.exitValue();
            log.debug("2.执行结果:{}", exitValue);

        } catch (Exception e) {
            log.error("3.运行任务失败,params:" + params + "");
            e.printStackTrace();
            return FAIL;
            //throw e;
        } finally {
            log.debug("3.运行结束");
            if (p != null) {
                p.destroy();
            }


        }
        return exitValue;
    }


    /**
     * @param params  新进程参数
     * @param logFlag 主线程是否接收日志 1:是 0:否
     */
    public static List<String> runJobCmdGet(List<String> params, boolean logFlag) {

        List<String> strList = new ArrayList<>();

        int exitValue;
        StringBuilder value = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(params);
        builder.redirectErrorStream(true);
        Process p = null;
        log.debug("进入挂起主线程时显示参数:{}", params);
        try {
            p = builder.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String tempLine = null;
            while ((tempLine=br.readLine()) != null) {

                strList.add(tempLine);
                log.debug("结果展示：{}", tempLine);
            }
//            if (logFlag) {
//                new CleanInputCache(p.getInputStream(), "INFO").start();
//                new CleanInputCache(p.getErrorStream(), "ERROR").start();
//            }
            //将当前线程等待，直到执行完成.
            p.waitFor();

            log.debug("1.是否挂起主线程?");


            exitValue = p.exitValue();
            log.debug("2.执行结果:{}", exitValue);

        } catch (Exception e) {
            log.error("3.运行任务失败,params:" + params + "");
            e.printStackTrace();
            return strList;
            //throw e;
        } finally {
            log.debug("3.运行结束");
            if (p != null) {
                p.destroy();
            }


        }

        return strList;
    }

    /**
     * @param cmd         新进程参数
     * @param waitForFlag para_flag: 1－等待　０－不等待
     * @param logFlag     主线程是否接收日志 1:是 0:否
     */
    public static int runJobCmd(String cmd, boolean waitForFlag, boolean logFlag) {
        int exitValue;
        Runtime run = Runtime.getRuntime();

        Process p = null;

        try {
            p = run.exec(cmd);
//            if (logFlag) {
//                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
//                String line;
//                while ((line = br.readLine()) != null) {
//                    if (line.toLowerCase().contains("error") || line.toLowerCase().contains("fail")) {
//                        log.error(line);
//                    } else {
//                        log.info(line);
//                    }
//                }
//            }
            new CleanInputCache(p.getInputStream(), "INFO").start();
            new CleanInputCache(p.getErrorStream(), "ERROR").start();
            //将当前线程等待，直到执行完成.
            //if(waitForFlag){
            //设置最长等待时间

            //}
            log.debug("是否挂起主线程?");
            if (p.waitFor() == 0) {
                exitValue = p.exitValue();
                log.debug("是否挂起主线程 :{}", exitValue);
            } else {
                exitValue = p.exitValue();
                log.debug("是否挂起主线程 :{}", exitValue);
            }


        } catch (Exception e) {
            log.error("运行任务失败,params:" + cmd + "");
            e.printStackTrace();
            return FAIL;
            //throw e;
        } finally {
            log.debug("运行结束");
            if (p != null)
                p.destroy();
        }


        return exitValue;
    }


    public static String getEtlSysPath() {
        String sysDir = System.getenv("ETLPATH");
        if (sysDir == null || sysDir.trim().length() == 0)
            sysDir = System.getenv("HOME");
        return sysDir;
    }


    public static List<FileDirVO> strToFileDirVO(List<String> stringList) {
        List<FileDirVO> fileDirVOList = new ArrayList<>();


        stringList.forEach(item -> {

            if (item != null && !StringUtil.isEmpty(item)) {
                String[] f = item.split(" ");
                FileDirVO vo = new FileDirVO();
                List<String> fList = new ArrayList<>();
                for (int i = 0; i < f.length; i++) {

                    if (f[i].length() != 0) {
                        fList.add(f[i]);
                    }
                }
                for (int i = 0; i < fList.size(); i++) {
                    switch (i) {
                        case 0:
                            if (fList.get(i).contains("dr")) {
                                //查看文件目录
                                vo.setFileType("1");
                            } else if (fList.get(i).contains("-rw")) {
                                //查看文件
                                vo.setFileType("2");
                            } else {
                                //查看目录
                                vo.setFileType("0");
                            }
                            break;
                        case 1:
                            vo.setFileNumber(fList.get(i));
                            break;
                        case 2:
                            vo.setOwner(fList.get(i));
                            break;
                        case 3:
                            vo.setUserGroup(fList.get(i));
                            break;
                        case 4:
                            vo.setFileSize(fList.get(i));
                            break;
                        case 5:
                            vo.setCreateMonth(fList.get(i));
                            break;
                        case 6:
                            vo.setCreateDay(fList.get(i));
                            break;
                        case 7:
                            vo.setCreateTime(fList.get(i));
                            break;
                        case 8:
                            vo.setFileName(fList.get(i));
                            break;
                        default:
                            break;
                    }
                }

                fileDirVOList.add(vo);
            }

        });


        return fileDirVOList;
    }


}

@Slf4j
class CleanInputCache extends Thread {

    private InputStream is;
    private String type;

    public CleanInputCache(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    @Override
    public void run() {
        try {
//            super.run();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                log.info(line);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }
}


